package files_controller_with_factory;
import java.io.*;
import org.apache.log4j.Logger;

public class FindCommandExecutor implements ICommandExecutor{ 
	private static final Logger cont_log = Logger.getLogger("control");
	
	public void execute(String string){
		String[] str_mas = string.split(" ");
		String path = str_mas[1];
		String search_word = str_mas[2];
		cont_log.info("Search...");
		inner_execute(path,search_word, 1);				
	}
	
	private void inner_execute(String path, String search_word, int nest){
		File folder = new File(path);
		if (!folder.exists()){
			cont_log.warn("Directory not found: " + path);		
		}else{
			StringBuilder gap = new StringBuilder();
			for (int i = 0; i < nest; i++){
				gap.append(' ');
		   }
			File[] list = folder.listFiles();			
			for(File file : list){
				if(file.isDirectory()){
					if((file.getName().contains(search_word))) {
						//cont_log.info(gap.toString() + "<dir> " + file.getName() + " in " + folder.toString());
						System.out.println(gap.toString() + "<dir> " + file.getName() + " in " + folder.toString());
						}
					inner_execute(file.toString(), search_word, nest+1);
				}else if(file.isFile()){
					if((file.getName().contains(search_word))) {
						//cont_log.info(gap.toString() + "<file> " + file.getName() +" in " + folder.toString());
						System.out.println(gap.toString() + "<file> " + file.getName() +" in " + folder.toString());
						}
				}
			}
		}			
	}
	
	private static FindCommandExecutor instance;
	private FindCommandExecutor(){		
	}
	public static ICommandExecutor getInstance(){
		if(instance==null){
			instance = new FindCommandExecutor();
		}
		return instance;
	}
	

}
